<template>
  <div class="main">
    <div class="air-column">
      <h2>乘机人</h2>

      <!-- 一、动态增减表单项中，model动态绑定一个自定义命名的表单数据对象 -->
      <!-- 这里使用users命名原因：1.语义化  2.ES6简化代码 -->
      <!--  -->
      <!-- 二、实现整个页面的表单验证，需要使用ref双向绑定dom元素 -->
      <el-form class="member-info" :model="{users}" ref="usersForm">
        <div class="member-info-item" v-for="(item,index) in users" :key="index">
          <el-form-item
            label="乘机人"
            :prop="`users[${index}].username`"
            :rules="[
            { required: true, message: '乘机人姓名不能为空', trigger: 'blur' },
            { pattern:/[a-zA-Z]{2,20}|[\u4e00-\u9fa5]{2,10}/, message: '联系人姓名不合法', trigger: 'blur' },
          ]"
          >
            <el-input placeholder="姓名" v-model="item.username" class="input-with-select"></el-input>
          </el-form-item>

          <el-form-item
            label="证件类型"
            :prop="`users[${index}].id`"
            :rules="[
            { required: true, message: '乘机人身份证不能为空', trigger: 'blur' },
            { pattern:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '乘机人身份证不合法', trigger: 'blur' },
          ]"
          >
            <el-input placeholder="证件号码" v-model="item.id" class="input-with-select">
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="身份证" value="1" :checked="true"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers">添加乘机人</el-button>
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <div>
        <div class="insurance-item" v-for="item in ticketChooseList.insurances" :key="item.id">
          <el-checkbox-group v-model="insuranceData">
            <el-checkbox
              :label="item.id"
              border
            >{{ `${item.type}：￥${item.price}/份×${users.length} 最高赔付${item.compensation}万` }}</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
    </div>

    <div class="air-column">
      <h2>发票</h2>
      <el-checkbox-group v-model="invoice">
        <el-checkbox label="是否需要发票" border></el-checkbox>
      </el-checkbox-group>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          label-width="68px"
          :model="{
          contactName,
          contactPhone,
          captcha
        }"
          :rules="contactRules"
          ref="contactForm"
        >
          <el-form-item label="姓名" prop="contactName">
            <el-input v-model="contactName"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input placeholder="请输入内容" v-model="contactPhone">
              <template slot="append">
                <el-button @click="handleSendCaptcha">发送验证码</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="captcha"></el-input>
          </el-form-item>
        </el-form>

        <!-- 判断vuex中是否保存了用户token来决定提交按钮是否显示 -->
        <el-button
          type="warning"
          class="submit"
          @click="handleSubmit"
          v-if="$store.state.user.userInfo.token"
        >提交订单</el-button>
      </div>
    </div>

    <div class="air-column" v-if="!$store.state.user.userInfo.token">
      <span class="loginTips">温馨提示：亲爱的客官，你还未登录哦，登录后再提交订单吧~</span>

      <el-row type="flex" justify="center" align="middle" class="loginBox">
        <div class="form">
          <div class="formTabs">
            <div
              class="formTabs_item"
              v-for="(item,index) in ['登 录','注 册']"
              :key="index"
              @click="changeTab(index)"
              :class="{active:currentTab==index}"
            >
              <div>{{ item }}</div>
            </div>
          </div>

          <!-- 登录组件 -->
          <loginForm v-if="currentTab==0" />

          <!-- 注册组件 -->
          <!-- 通过子组件发射，父组件接受并执行将0赋值给tab展示登录页 -->
          <registerForm @goToLogin="currentTab = 0" v-if="currentTab==1" />
        </div>
      </el-row>
    </div>
  </div>
</template>

<script>
import loginForm from "@/components/user/loginForm";
import registerForm from "@/components/user/registerForm";

export default {
  components: {
    loginForm,
    registerForm
  },

  data() {
    return {
      users: [
        {
          username: "",
          id: ""
        }
      ],
      // 保险选项数据
      insuranceData: [1, 2],
      // 联系人数据
      contactName: "",
      contactPhone: "",
      captcha: "",
      invoice: "",
      // 联系人的规则
      contactRules: {
        contactName: [
          { required: true, message: "联系人姓名不能为空", trigger: "blur" },
          {
            pattern: /[a-zA-Z]{2,20}|[\u4e00-\u9fa5]{2,10}/,
            message: "联系人姓名不合法",
            trigger: "blur"
          }
        ],

        contactPhone: [
          {
            required: true,
            message: "联系人的手机号码不能为空",
            trigger: "blur"
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号码格式错误",
            trigger: "blur"
          }
        ],

        captcha: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur"
          }
        ]
      },
      // 当前tab
      currentTab: 0
    };
  },

  props: {
    ticketChooseList: Object
  },

  methods: {
    // 添加乘机人
    handleAddUsers() {
      this.users.push({
        username: "",
        id: ""
      });
    },

    // 移除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1);
    },

    // 发送手机验证码
    handleSendCaptcha() {
      // console.log(this.contactPhone);
      // console.log(/^1[3-9]\d{9}$/.test(this.contactPhone));

      // 判断手机号码是否有填写，如果没填
      // 终止发送验证码请求
      if (!this.contactPhone) {
        this.$message({
          message: "请填写手机号码",
          type: "warning"
        });

        return;
      }

      // 如果手机号码格式不对
      // 也需要终止发送验证码请求
      if (!/^1[3-9]\d{9}$/.test(this.contactPhone)) {
        return;
      }

      this.$axios({
        url: "/captchas",
        method: "POST",
        data: {
          tel: this.contactPhone
        }
      }).then(res => {
        console.log("手机验证码返回的数据", res);

        if (res.data.code == "000000") {
          this.$message.success(`您的验证码是:${res.data.code}`);
        }
      });
    },

    // 提交订单
    async handleSubmit() {
      // 对整个表单进行校验

      // 参数为一个回调函数,该回调函数会在校验结束后被调用，并传入两个参数：
      // 是否校验成功和未通过校验的字段。
      // this.$refs.usersForm.validate((isValid) => {
      //   console.log('是否通过',isValid);
      // });

      // 若不传入回调函数，则会返回一个 promise
      // this.$refs.usersForm.validate().then(isValid=>{
      //   console.log('是否通过',isValid);
      // }).catch(error=>{
      //   console.log('错误信息',error);
      // })

      // 赋值变量给promise，以便校验后是否发送提交请求
      // 乘机人表单校验
      let usersFormValid = await this.$refs.usersForm.validate().catch(e => {});
      console.log(usersFormValid);
      // 联系人表单校验
      let usersContactForm = await this.$refs.contactForm
        .validate()
        .catch(e => {});
      console.log(usersFormValid);

      // 校验页面所有表单
      if (usersFormValid && usersContactForm) {
        // 拼接以上表单内所有的数据
        const data = {
          users: this.users,
          insurances: this.insuranceData,
          contactName: this.contactName,
          contactPhone: this.contactPhone,
          invoice: this.invoice,
          seat_xid: this.$route.query.seat_xid,
          air: this.$route.query.id,
          captcha: this.captcha
        };

        // 发送提交订单的请求
        this.$axios({
          url: "/airorders",
          method: "POST",
          data,
          headers: {
            Authorization: "Bearer " + this.$store.state.user.userInfo.token
          }
        })
          .then(res => {
            console.log("提交机票订单的返回结果", res);

            const { message } = res.data;
            const { id } = res.data.data;

            // 跳转到支付页
            if(message === "订单提交成功"){
                this.$router.push(`/air/pay/?id=${id}`)

                this.$message.success('订单提交成功')
            }
          })
          .catch(error => {});
      }
    },

    // 计算总价的函数
    getTotalPrice() {
      // 初始化总价
      let total = 0;

      // 1，加上所有乘机人的机票费用
      total +=
        this.ticketChooseList.seat_infos.org_settle_price * this.users.length;

      // 2.计算所有乘机人的保险费用
      // 遍历所有保险项，如果发现id存在被选中的列表中，就要乘以乘机人数量，累加到结果中
      this.ticketChooseList.insurances.forEach(element => {
        if (this.insuranceData.indexOf(element.id) >= 0) {
          total += element.price * this.users.length;
        }
      });

      // 3.计算所有乘机人的机建＋燃油
      total += this.ticketChooseList.airport_tax_audlet * this.users.length;

      // 打印出总价
      console.log("打印总价", total);

      // 将总价发射到父组件中
      // 以便侧边栏兄弟组件接收表单组件的传值
      this.$emit("getTotalPrice", total);
    },

    // 计算乘机人的数组长度
    getUsersLength() {
      const getUsersNum = this.users.length;

      // 打印乘机人的数组长度
      console.log("打印乘机人的数组长度", getUsersNum);

      // 将乘机人的数组长度发射到父组件中
      // 以便侧边栏兄弟组件接收表单组件的传值
      this.$emit("getUsersLength", getUsersNum);
    },

    // 计算保险总价
    getInsurancesPrice() {
      // 初始化保险价格
      let insurancesTotal = 0;

      this.ticketChooseList.insurances.forEach(element => {
        if (this.insuranceData.indexOf(element.id) >= 0) {
          insurancesTotal += element.price * this.users.length;
        }
      });

      // 打印出总价
      console.log("打印保险总价", insurancesTotal);

      // 发射保险总价给父组件
      // 以便侧边栏兄弟组件接收表单组件的传值
      this.$emit("getInsurancesPrice", insurancesTotal);
    },

    // 登录注册页切换
    changeTab(index) {
      this.currentTab = index;
    }
  },

  // mounted () {
  //   console.log('保险价格',this.getInsurancesPrice());
  // },

  watch: {
    // 监听每当乘机人发生了变化，需要重新计算一个总价
    // users(){
    //   this.getTotalPrice();
    // },

    // 如果需要其他属性设置，那么就使用深度监听
    // 设置属性immediate 可以让监听器一开始就执行一次
    users: {
      handler() {
        this.getTotalPrice();
        this.getUsersLength();
        this.getInsurancesPrice();
      },
      immediate: true
    },

    // 监听每当保险发生了变化，需要重新计算一个总价
    // insuranceData() {
    //   this.getTotalPrice();
    // }

    insuranceData: {
      handler() {
        this.getTotalPrice();
        this.getUsersLength();
        this.getInsurancesPrice();
      },
      immediate: true
    }
  }
};
</script>

<style scoped lang="less">
.main {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  padding: 20px 50px 20px 20px;
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.2);
}

.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 540px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}

.loginTips {
  font-size: 12px;
  border: 1px solid #fff5e6;
  background-color: #fff5e6;
  padding: 6px 8px 6px 14px;
  border-radius: 14px;
  color: #ff8300;
  margin-bottom: 16px;
}

.loginBox {
  flex-direction: column;
  height: 100%;
  margin: 30px 0px 10px 0px;

  .form {
    display: flex;
    border: 2px #ddd dashed;

    .formTabs {
      &_item {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f4f4f5;
        width: 70px;
        height: 220px;
        line-height: 40px;
        font-weight: 700;
        font-size: 18px;
        // border-radius: 16px 0 0 0;

        // &:last-child {
        //   border-radius: 0 0 0 16px;
        // }

        div {
          width: 20px;
        }
      }

      .active {
        background-color: rgba(235, 229, 228, 0.1);
      }
    }

    .loginForm,.registerForm{
      background-color: rgba(235, 229, 228, 0.1);
    }
  }
}
</style>